package com.rayo.accesscontrollercopy.module.setting;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.rayo.accesscontrollercopy.R;
import com.rayo.accesscontrollercopy.app.ActivityManager;
import com.rayo.accesscontrollercopy.app.BaseFragment;
import com.rayo.accesscontrollercopy.module.setting.presenter.ParamPresenter;
import com.rayo.accesscontrollercopy.module.setting.view.IParamView;
import com.rayo.accesscontrollercopy.module.welcome.WelcomeActivity;
import com.rayo.accesscontrollercopy.utils.KeyBoardUtils;
import com.rayo.accesscontrollercopy.utils.PreferencesUtils;


/**
 * Created by yanghaojie on 16/7/21.
 */
public class ParamFragment extends BaseFragment implements IParamView, AdapterView.OnItemSelectedListener, TextView.OnEditorActionListener {
    private Spinner mSpDateTime, mSpLang, mSpNameOrder, mSpTimeliness;
    private Button mBtnAbout, mBtnOfficeMode, mBtnOpen, mBtnReset,mBtnSetKeyBox;
    private EditText mEdtOpenTime;

    private ParamPresenter presenter;
    private ArrayAdapter<String> mDtFormatArray, mLangArray, mNameOrderArray, mTimelinessArray;

    private static final int OPEN_MAX_TIME = 60;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_param;
    }

    @Override
    protected void setupViews() {
        mSpDateTime = (Spinner) rootView.findViewById(R.id.spinner_date_format);
        mSpLang = (Spinner) rootView.findViewById(R.id.spinner_lang);
        mSpNameOrder = (Spinner) rootView.findViewById(R.id.spinner_name_order);
        mSpTimeliness = (Spinner) rootView.findViewById(R.id.spinner_timeliness);
        mBtnAbout = (Button) rootView.findViewById(R.id.btn_version);
        mBtnAbout.setOnClickListener(this);
        mBtnOfficeMode = (Button) rootView.findViewById(R.id.btn_office_mode);
        mBtnOfficeMode.setOnClickListener(this);
        mBtnOpen = (Button) rootView.findViewById(R.id.btn_open_controller);
        mBtnOpen.setOnClickListener(this);
        mEdtOpenTime = (EditText) rootView.findViewById(R.id.edit_open_time);
        mEdtOpenTime.setOnEditorActionListener(this);
        mEdtOpenTime.setHint(getString(R.string.setting_open_time_max, OPEN_MAX_TIME));
        mBtnReset = (Button) rootView.findViewById(R.id.btn_reset);
        mBtnReset.setOnClickListener(this);
        mBtnSetKeyBox = rootView.findViewById(R.id.btn_setkeybox);
        mBtnSetKeyBox.setOnClickListener(this);
    }


    @Override
    protected void initialized() {
        presenter = new ParamPresenter(getContext(), this);
        mDtFormatArray = new ArrayAdapter<>(getContext(), R.layout.support_simple_spinner_dropdown_item,
                getResources().getStringArray(R.array.data_time_format));
        mSpDateTime.setAdapter(mDtFormatArray);
        mLangArray = new ArrayAdapter<>(getContext(), R.layout.support_simple_spinner_dropdown_item,
                getResources().getStringArray(R.array.lang));
        mSpLang.setAdapter(mLangArray);
        mNameOrderArray = new ArrayAdapter<>(getContext(), R.layout.support_simple_spinner_dropdown_item,
                getResources().getStringArray(R.array.name_order));
        mSpNameOrder.setAdapter(mNameOrderArray);
        mTimelinessArray = new ArrayAdapter<>(getContext(), R.layout.support_simple_spinner_dropdown_item,
                getResources().getStringArray(R.array.timeliness));

        presenter.initData();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_version:
                presenter.getVersion();
                break;
            case R.id.btn_office_mode:
                presenter.officeMode();
                break;
            case R.id.btn_open_controller:
                presenter.openController();
                break;
            case R.id.btn_reset:
                new AlertDialog.Builder(getContext()).setTitle(R.string.app_name).setMessage(R.string.setting_lock_id_first)
                        .setIcon(R.mipmap.ic_launcher).setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PreferencesUtils.putBoolean(getActivity(),"isFirst",false);
                        PreferencesUtils.putBoolean(getActivity(), "isdbname", false);
                        presenter.reset();
                    }
                }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                }).show();

                break;
            case R.id.btn_setkeybox:
                getActivity().startActivity(new Intent(getActivity(),SetBoxActivity.class));

                break;
            default:
                break;
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.spinner_date_format:
                presenter.saveDtFormat(position);
                break;
            case R.id.spinner_lang:
                presenter.saveLang(position);
                break;
            case R.id.spinner_name_order:
                presenter.saveNameOrder(position);
                break;
            case R.id.spinner_timeliness:
                presenter.saveTimeliness(position);
                break;
            default:
                break;
        }

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        switch (v.getId()) {
            case R.id.edit_open_time:
                if (EditorInfo.IME_ACTION_DONE == actionId || (null != event
                        && KeyEvent.KEYCODE_ENTER == event.getKeyCode())) {
                    KeyBoardUtils.closeKeybord(v, getContext());
                    int second = Integer.valueOf(v.getText().toString().trim());
                    if (second <= OPEN_MAX_TIME)
                        presenter.saveOpenTime(second);
                    else {
                        v.setText("");
                        showShortSnackbar(rootView, R.string.setting_exceed_max, null);
                    }
                }
                return true;
            default:
                break;
        }
        return false;
    }

    @Override
    public void showProgressBar(boolean isShow) {

    }

    @Override
    public void showSnackBar(String txt) {
        if (!TextUtils.isEmpty(txt)) showShortSnackbar(rootView, txt, null);
        else if (txt != null && txt.equals(""))
            showShortSnackbar(rootView, "", null);
    }

    @Override
    public void showAlertDialog(String txt) {
        if (null != txt)
            new AlertDialog.Builder(getContext()).setTitle(R.string.app_name).setMessage(txt)
                    .setIcon(R.mipmap.ic_launcher).setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).show();
    }

    @Override
    public void setParamInfo(int dt, int lang, int name, int timeliness, int openTime) {

        if (null != mSpDateTime && null != mDtFormatArray && mDtFormatArray.getCount() > dt)
            mSpDateTime.setSelection(dt, true);
        if (null != mSpLang && null != mLangArray && mLangArray.getCount() > lang)
            mSpLang.setSelection(lang, true);
        if (null != mSpNameOrder && null != mNameOrderArray && mNameOrderArray.getCount() > name) {
            mSpNameOrder.setSelection(name, true);
        }
//        if (null != mSpTimeliness && null != mTimelinessArray && mTimelinessArray.getCount() > dt)
//            mSpTimeliness.setSelection(timeliness, true);
        if (0 == openTime)
            mEdtOpenTime.setText("");
        else
            mEdtOpenTime.setText(String.valueOf(openTime));

        mSpDateTime.setOnItemSelectedListener(this);
        mSpLang.setOnItemSelectedListener(this);
        mSpNameOrder.setOnItemSelectedListener(this);
//        mSpTimeliness.setOnItemSelectedListener(this);
    }

    @Override
    public void restartApp() {
        Intent intent = new Intent(mContext, WelcomeActivity.class);
        PendingIntent restartIntent = PendingIntent.getActivity(mContext
                , 0, intent,PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager mgr = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 500,
                restartIntent);
        ActivityManager.getInstance().closeAllActivity();
        System.exit(0);
    }


}
